var createError = require('http-errors');
var express = require('express');
var bodyParser = require("body-parser")
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var authRouter = require('./routes/auth');
var usersRouter = require('./routes/users');
var wikiRouter = require('./routes/wiki');
var productsRouter = require('./routes/products');

var app = express();

// 环境配置
const config = require('./config');

// CORS配置
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : '*',
  credentials: true
}));

// 日志配置
if (config.env === 'production') {
  app.use(logger('combined'));
} else {
  app.use(logger('dev'));
}

// 中间件配置
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: false, limit: '10mb' }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 静态文件服务（生产环境可选）
if (config.env === 'development') {
  app.use(express.static(path.join(__dirname, 'public')));
}

// API路由 - 添加/api前缀
app.use('/api', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/auth', loginRouter);
app.use('/api/wiki', wikiRouter);
app.use('/api/products', productsRouter);
app.use('/api/authNew', authRouter);

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    environment: config.env
  });
});

// API文档接口
app.get('/api', (req, res) => {
  res.json({
    message: 'Express API Server',
    version: '1.0.0',
    endpoints: {
      auth: {
        login: 'POST /api/auth/login',
        register: 'POST /api/auth/register'
      },
      users: 'GET /api/users',
      wiki: 'GET /api/wiki',
      health: 'GET /health'
    }
  });
});

// 404处理
app.use(function(req, res, next) {
  res.status(404).json({
    code: 404,
    msg: '接口不存在',
    path: req.path
  });
});

// 错误处理中间件
app.use(function(err, req, res, next) {
  console.error('错误:', err);

  // 设置状态码
  const status = err.status || 500;

  // 错误响应
  const errorResponse = {
    code: status,
    msg: err.message || '服务器内部错误',
    ...(config.env === 'development' && { stack: err.stack })
  };

  res.status(status).json(errorResponse);
});

module.exports = app;
